package com.istock.user.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.istock.base.common.api.model.ApiBaseResponse;
import com.istock.base.common.api.model.PageInfo;
import com.istock.base.common.api.model.RetStatusEnum;
import com.istock.union.user.client.SSOClientUtils;
import com.istock.union.user.model.Constants;
import com.istock.union.user.model.OperLog;
import com.istock.union.user.model.RoleInfo;
import com.istock.union.user.model.RoleInfoModel;
import com.istock.union.user.model.RoleInfoQueryModel;
import com.istock.union.user.model.SecurityChecker;
import com.istock.union.user.service.RoleInfoService;
import com.istock.union.user.service.TenantInfoService;


@RequestMapping("/s/roleInfo")
@Controller
public class RoleInfoController {

	private static final Logger logger = LoggerFactory.getLogger(RoleInfoController.class);
	
	@Autowired
	private RoleInfoService roleService;
	@Autowired
	private TenantInfoService tenantInfoService;
	
	@SecurityChecker("user:roleInfo:search")
	@RequestMapping("/showList")
	public String role(ModelMap model) {
		model.put("tenantList", tenantInfoService.findAllTenantList());
		return "user-app/roleInfo/list";
	}

	@SecurityChecker("user:roleInfo:search")
	@RequestMapping("/search")
	@ResponseBody
	@OperLog(functionName="查询",menuName="角色管理")
	public ApiBaseResponse<PageInfo<RoleInfo>> search(RoleInfoQueryModel role, PageInfo<RoleInfo> page) {
		if (page == null) {
			page = new PageInfo<RoleInfo>();
		}
		roleService.selectRoleListByPage(role, page);
		return new ApiBaseResponse<PageInfo<RoleInfo>>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE, 
				Constants.API_RESPONSE_SUCCESS_MESSAGE, page);
	}

	/**
	 * 新增
	 */
	@RequestMapping("/addPre")
	public String add(ModelMap model) {
		if (SSOClientUtils.getInstance().isAdmin()) {
			model.put("tenants", tenantInfoService.findAllTenantList());
		}
		return "user-app/roleInfo/add";
	}

	/**
	 * 新增保存角色
	 */
	@SecurityChecker("user:roleInfo:add")
	@RequestMapping("/add")
	@ResponseBody
	@OperLog(functionName="新增",menuName="角色管理")
	public ApiBaseResponse<Boolean> addSave(RoleInfoModel role) {
		try {
			role.setCreateBy(SSOClientUtils.getInstance().findCurrentUser().getLoginName());
			roleService.insertRole(role);
		} catch (Exception e) {
			logger.error("insert role info error ", e);
			return new ApiBaseResponse<Boolean>(RetStatusEnum.FAIL,Constants.API_RESPONSE_FAIL_CODE,  Constants.API_RESPONSE_FAIL_MESSAGE, false);
		}
		return new ApiBaseResponse<Boolean>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE,  Constants.API_RESPONSE_SUCCESS_MESSAGE, true);
	}
	
	/**
	 * 修改角色
	 */
	@RequestMapping("/editPre")
	public String edit(ModelMap model, String id) {
		model.put("role", roleService.selectRoleById(id));
		return "user-app/roleInfo/edit";
	}

	/**
	 * 修改保存角色
	 */
	@SecurityChecker("user:roleInfo:edit")
	@RequestMapping("/edit")
	@ResponseBody
	@OperLog(functionName="修改角色菜单",menuName="角色管理")
	public ApiBaseResponse<Boolean> editSave(RoleInfoModel role) {
		try {
			role.setUpdateBy(SSOClientUtils.getInstance().findCurrentUser().getLoginName());
			roleService.updateRole(role);
		} catch (Exception e) {
			logger.error("insert role info error ", e);
			return new ApiBaseResponse<Boolean>(RetStatusEnum.FAIL,Constants.API_RESPONSE_FAIL_CODE,  Constants.API_RESPONSE_FAIL_MESSAGE, false);
		}
		return new ApiBaseResponse<Boolean>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE,  Constants.API_RESPONSE_SUCCESS_MESSAGE, true);
	}
	
	/**
	@SecurityChecker("user:roleInfo:export")
	@RequestMapping("/export")
    @ResponseBody
    public ApiBaseResponse<?> export(RoleInfo role) {
        List<RoleInfo> list = roleService.selectRoleList(role);
        List<RoleInfoVO> voList = BeanUtils.propertiesCopy(list, new RoleInfoVO());
        ExcelUtil<RoleInfoVO> util = new ExcelUtil<RoleInfoVO>(RoleInfoVO.class);
        return util.exportExcel(voList, "角色数据");
    }
    */
	
	/**
     * 新增数据权限
     */
	@RequestMapping("/rulePre")
    public String rule(ModelMap model, String id) {
		model.put("role", roleService.selectRoleById(id));
        return "user-app/roleInfo/rule";
    }

    /**
     * 修改保存数据权限
     */
	@SecurityChecker("user:roleInfo:edit")
    @RequestMapping("/rule")
    @ResponseBody
    @OperLog(functionName="修改角色组织机构",menuName="角色管理")
    public ApiBaseResponse<Boolean> ruleSave(RoleInfoModel role) {
		try {
			role.setUpdateBy(SSOClientUtils.getInstance().findCurrentUser().getUserName());
			roleService.updateRole(role);
		} catch (Exception e) {
			logger.error("update role info error ", e);
			return new ApiBaseResponse<Boolean>(RetStatusEnum.FAIL,Constants.API_RESPONSE_FAIL_CODE,  Constants.API_RESPONSE_FAIL_MESSAGE, false);
		}
		return new ApiBaseResponse<Boolean>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE,  Constants.API_RESPONSE_SUCCESS_MESSAGE, true);
    }
	
	/**
	 * 删除角色
	 */
	@SecurityChecker("user:roleInfo:remove")
	@RequestMapping("/remove")
	@ResponseBody
	@OperLog(functionName="删除",menuName="角色管理")
	public ApiBaseResponse<Boolean> remove(String ids) {
		// 实际更新了标识为失效
		try {
			roleService.deleteRoleByIds(ids);
		} catch (Exception e) {
			logger.error("delete role info error ", e);
			return new ApiBaseResponse<Boolean>(RetStatusEnum.FAIL,Constants.API_RESPONSE_FAIL_CODE,  Constants.API_RESPONSE_FAIL_MESSAGE, false);
		}
		return new ApiBaseResponse<Boolean>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE,  Constants.API_RESPONSE_SUCCESS_MESSAGE, true);
	}
	
	/**
	 * 校验角色名称
	 */
	@RequestMapping("/checkRoleNameUnique")
	@ResponseBody
	public ApiBaseResponse<Boolean> checkRoleNameUnique(RoleInfo role) {
		return new ApiBaseResponse<Boolean>( RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE,
				Constants.API_RESPONSE_SUCCESS_MESSAGE, roleService.checkRoleNameUnique(role));
	}
	
	/**
	 * 校验角色编号
	 */
	@RequestMapping("/checkRoleKeyUnique")
	@ResponseBody
	public ApiBaseResponse<Boolean> checkRoleKeyUnique(RoleInfo role) {
		return new ApiBaseResponse<Boolean>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE, 
				Constants.API_RESPONSE_SUCCESS_MESSAGE, roleService.checkRoleKeyUnique(role));
	}
	
	/**
     * 角色状态修改
     */
	@SecurityChecker("user:roleInfo:edit")
    @RequestMapping("/changeStatus")
    @ResponseBody
    @OperLog(functionName="修改状态",menuName="角色管理")
    public ApiBaseResponse<Boolean> changeStatus(RoleInfo role) {
//		if (role.getStatus() == Constants.COMMON_INVALID) {
			long count = roleService.countRoleUsersByRoleId(role.getId());
			if (count > 0) {
				return new ApiBaseResponse<Boolean>(RetStatusEnum.FAIL,Constants.API_RESPONSE_FAIL_CODE,  "存在使用中的用户，不允许变更为失效", false);
			}
//		}
		// 实际更新了标识为失效
		try {
			role.setUpdateBy(SSOClientUtils.getInstance().findCurrentUser().getUserName());
			roleService.updateRoleInfo(role);
		} catch (Exception e) {
			logger.error("update role info error ", e);
			return new ApiBaseResponse<Boolean>(RetStatusEnum.FAIL,Constants.API_RESPONSE_FAIL_CODE,  Constants.API_RESPONSE_FAIL_MESSAGE, false);
		}
		return new ApiBaseResponse<Boolean>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE,  Constants.API_RESPONSE_SUCCESS_MESSAGE, true);
    }
	
	@RequestMapping("/findTenantRoleList")
	@ResponseBody
	public List<RoleInfo> findTenantRoleList(String tenantCode){
		RoleInfoQueryModel queryModel = new RoleInfoQueryModel();
		queryModel.setTenantCode(tenantCode);
		return roleService.selectRoleList(queryModel);
	}
}
